﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Mystery.SharePoint
{
	class SiteManagementJob : SPJobDefinition
	{
		public const string JobName = "spm-sitemanagement";
		/// <summary>
		/// The name to use for display purposes
		/// </summary>
		public override string DisplayName
		{
			get { return Resources.JobDefinition_SiteManagement_DisplayName; }
		}
		/// <summary>
		/// A description of what the job does
		/// </summary>
		public override string Description
		{
			get { return Resources.JobDefinition_SiteManagement_Description; }
		}
		[Obsolete("Do not use. provided for serialization framework", true)]
		public SiteManagementJob()
		{
		}
		/// <summary>
		/// Constructs the timer job
		/// </summary>
		/// <param name="application">The application the job is connected to</param>
		public SiteManagementJob(SPWebApplication application)
			: base(JobName, application, null, SPJobLockType.Job)
		{
			base.Schedule = SPSchedule.FromString("daily between 01:00:00 and 05:00:00");
		}

		public override void Execute(Guid targetInstanceId)
		{
			// find the url of the web application, used to find the root site collection and as a basis to create 
			// site collection paths
			Uri uri = base.WebApplication.GetResponseUri(SPUrlZone.Default);
			string[] relativeUrls = base.WebApplication.Sites.Names;

			Logger.L.AddInformation(Category.Administration,
				"Starting site management operation on {0}", uri);

			// get a reference to the root site collection
			using (SPSite rootSite = new SPSite(uri.ToString()))
			{
                SiteManagementOperation operation = new SiteManagementOperation(rootSite);

				//loop all contained site collection, ignoring root
				for (int i = 0; i < relativeUrls.Length; i++)
				{
					Uri absoluteUrl = new Uri(uri, relativeUrls[i]);
					SPSite site = null;
					try
					{
						site = new SPSite(absoluteUrl.ToString());
                        operation.Execute(site);
					}
					catch (System.IO.FileNotFoundException ex)
					{
						Logger.L.AddException(Category.Administration, ex, "Site collection {0} does not exist", absoluteUrl);
					}
					finally
					{
						if (site != null)
						{
							site.Dispose();
						}
					}
					UpdateProgress(i * 100 / relativeUrls.Length);
				}
			}
			Logger.L.AddInformation(Category.Administration,
				"Completing site management operation on {0}", uri);
		}
	}
}
